#include <stdio.h>

/* static const char *daytab[2] */
static const char daytab[2][13]
= {
    {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
    {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
};
;

static const char *month_name(int i)
{
    char *name[] = {
    "Illegal month",
    "January", "February", "March",
    "April",   "May",      "June",
    "July",    "August",   "September",
    "October", "November", "December"
    };
    i = (i > 12 || i < 0) ? 0 : i;
    return name[i];
}

int day_of_year(int year, int month, int day)
{
    int i, leap;
    char *contain_day;
    leap = year%4 == 0 && year%100 != 0 || year%400 == 0;
    contain_day = (char*)daytab[leap];
    if (month > 12 || day > daytab[leap][month])
        return -1;

    for (i = 1; i < month; i++)
        day += *++contain_day;
    return day;
}

int month_day(int year, int yearday, int *pmonth, int *pday)
{
    int i, leap;
    leap = year%4 == 0 && year%100 != 0 || year%400 == 0;
    char *contain_day = (char*)daytab[leap];
    for (i = 1; i < 12 && yearday > *++contain_day; i++)
        yearday -= *contain_day;
    if (i == 12 && yearday > *++contain_day) {
        *pmonth = -1;
        *pday = -1;
        return -1;
    }
    *pmonth = i;
    *pday = yearday;
}

int main(int argc, char *argv[])
{
    /* char a[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; */
    /* daytab[1] = a; */
    /* char b[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; */
    /* daytab[1] = b; */

    printf("2018/7/32 day of year: %d\n", day_of_year(2018, 7, 32));
    int month, day;
    month_day(2018, 388, &month, &day);
    printf("2018 388th day is %s %d\n", month_name(month), day);
    return 0;
}
